package com.neu.questionnaireplus.controller;

import cn.hutool.crypto.digest.MD5;
import com.neu.questionnaireplus.entity.HttpResponseEntity;
import com.neu.questionnaireplus.entity.Tenement;
import com.neu.questionnaireplus.service.MsmService;
import com.neu.questionnaireplus.service.TenementService;
import com.neu.questionnaireplus.utils.common.CommonUtils;
import com.neu.questionnaireplus.utils.constant.HttpStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Description: 使用swagger进行测试, url未使用rap2的，项目整合时再做修改
 * @Param:
 * @return:
 * @Author: ~FHX~ (:TSunS:)
 * @Date: 2022/10/30
 */
@RestController
@RequestMapping("/tenement")
@CrossOrigin
@Api("租户服务")
@Validated
public class TenementController {

  @Autowired
  private TenementService tenementService;

  @Autowired
  private MsmService msmService;

  /**
   * @Description: map用来暂时存储短信验证码，key是手机号，value是验证码 ,ConcurrentHashMap保障并发安全
   * @Param:
   * @return:
   * @Author: ~FHX~ (:TSunS:)
   * @Date: 2022/11/2
   */
  private Map<String, String> loginmap = new ConcurrentHashMap<String, String>();
  private Map<String, String> registermap = new ConcurrentHashMap<String, String>();
  private Map<String, String> resetPwdmap = new ConcurrentHashMap<String, String>();

  @ApiOperation("显示密保问题(传递回整个租户)")
  @RequestMapping(value = "/showTenementSec", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showTenementSec(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      Tenement tenement = tenementService.queryTenementByUsername(username);
      if (tenement != null && tenement.getStatus() != 1 && tenement.getDelFlag() != 1){
        httpResponseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(tenement)
            .setMessage("success");
      }else {
        httpResponseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户不存在或无法登录");
      }
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("注册租户时发送短信")
  @RequestMapping(value = "/registersmsTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity registerSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.registerSend("86" + phone);
      registermap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("租户登录时发送短信")
  @RequestMapping(value = "/loginSmsTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.loginSend("86" + phone);
      loginmap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("租户找回密码时发送短信")
  @RequestMapping(value = "/findPwdSmsTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity findPwdSms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String s = msmService.resetPwdSend("86" + phone);
      resetPwdmap.put(phone, s);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(s)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("管理员创建租户")
  @RequestMapping(value = "/createTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity createTenement(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String telnumber = map.get("telnumber").toString();
      Tenement tenement1 = new Tenement();
      tenement1
          .setDelFlag(0)
          .setStatus(0)
          .setCostNow((double) 0)
          .setHistoryCost((double) 0)
          .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
          .setId(CommonUtils.getUUID())
          .setPassword(MD5.create().digestHex(map.get("password").toString()))
          .setUsername(map.get("username").toString())
          .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
          .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
          .setTelnumber(telnumber);
      tenementService.insertTenement(tenement1);
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(tenement1)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  /**
   * @Description: 注意一个方法中的参数只能有一个RequestBody
   * @Param: [tenement, str]
   * @return: com.neu.questionnaireplus.entity.HttpResponseEntity
   * @Author: ~FHX~ (:TSunS:)
   * @Date: 2022/11/2
   */
  @ApiOperation("发送短信后注册")
  @RequestMapping(value = "/registerTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity registerTenement(@RequestBody Map<String, Object> map) {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      String telnumber = map.get("telnumber").toString();
      boolean b = tenementService.checkRegisterStr(telnumber, map.get("str").toString(),
          registermap.get(telnumber));
      if (b) {
        Tenement tenement1 = new Tenement();
        tenement1
            .setDelFlag(0)
            .setStatus(0)
            .setCostNow((double) 0)
            .setHistoryCost((double) 0)
            .setCreatedDate(CommonUtils.getDateByDateString(CommonUtils.getFormatDateTimeNow()))
            .setId(CommonUtils.getUUID())
            .setPassword(MD5.create().digestHex(map.get("password").toString()))
            .setUsername(map.get("username").toString())
            .setSecurityQuestionAnswer(map.get("securityQuestionAnswer").toString())
            .setSecurityQuestionContext(map.get("securityQuestionContext").toString())
            .setTelnumber(telnumber);
        tenementService.insertTenement(tenement1);
        httpResponseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(tenement1)
            .setMessage("success");
      } else {
        httpResponseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("验证码错误");
      }
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("通过密码登录")
  @RequestMapping(value = "/loginByPwdTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginByPwd(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      String password = map.get("password").toString();
      boolean b = tenementService.loginByPassword(username, MD5.create().digestHex(password));
      if (b) {
        Tenement tenement = tenementService.queryTenementByUsername(username);
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(tenement)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户名或密码错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("通过短信验证码登录")
  @RequestMapping(value = "/loginBySmsTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity loginBySms(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String phone = map.get("phone").toString();
      String str = map.get("str").toString();
      boolean b = tenementService.loginByPhone(phone, str, loginmap.get(phone));
      Tenement tenement = tenementService.queryTenementByPhone(phone);
      if (b) {
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(tenement)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("手机号或短信验证码错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("通过密保找回密码（验证密保）")
  @RequestMapping(value = "/checkSecTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity checkSec(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
      String username = map.get("username").toString();
      boolean b = tenementService.checkSecurityQuestion(username, securityQuestionAnswer);
      if (b) {
        responseEntity
            .setCode(HttpStatus.SUCCESS)
            .setData(b)
            .setMessage("success");
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("密保或用户名错误");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }


  @ApiOperation("找回密码（重置密码）")
  @RequestMapping(value = "/resetPwdTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity resetPwd(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      Tenement tenement = tenementService.queryTenementByUsername(username);
      if (tenement != null) {
        String newpassword = map.get("newpassword").toString();
        tenement.setPassword(MD5.create().digestHex(newpassword));
        boolean b = tenementService.updateTenement(tenement);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(tenement)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("修改失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("改变租户状态")
  @RequestMapping(value = "/changeTenementStatus", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity changeTenementStatus(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String username = map.get("username").toString();
      Tenement tenement = tenementService.queryTenementByUsername(username);
      if (tenement != null) {
        boolean b = tenement.getStatus() == 1 ? tenementService.freeTenement(tenement.getId()) : tenementService.forbiddenTenement(tenement.getId()) ;
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(tenement)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("租户状态改变失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("修改租户信息")
  @RequestMapping(value = "/updateTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity updateTenement(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
    try {
      String id = map.get("id").toString();
      Tenement tenement = tenementService.queryTenementByID(id);
      if (tenement != null) {
        String username = map.get("username").toString();
        String telnumber = map.get("telnumber").toString();
        String securityQuestionAnswer = map.get("securityQuestionAnswer").toString();
        String securityQuestionContext = map.get("securityQuestionContext").toString();
        Integer status = Integer.valueOf(map.get("status").toString());
        tenement
            .setUsername(username)
            .setTelnumber(telnumber)
            .setSecurityQuestionAnswer(securityQuestionAnswer)
            .setSecurityQuestionContext(securityQuestionContext)
            .setStatus(status);
        boolean b = tenementService.updateTenement(tenement);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(telnumber)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("修改失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("用户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }

  @ApiOperation("删除租户（伪删除）")
  @RequestMapping(value = "/deleteTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity deleteTenement(@RequestBody Map<String, Object> map) {
    HttpResponseEntity responseEntity = new HttpResponseEntity();
//    System.out.println(map.get("username").toString() + "   111   ");
    try {
      String username = map.get("username").toString();
      Tenement tenement = tenementService.queryTenementByUsername(username);
      if (tenement != null) {
        boolean b = tenementService.deleteTenementInfo(tenement);
        if (b) {
          responseEntity
              .setCode(HttpStatus.SUCCESS)
              .setData(tenement)
              .setMessage("success");
        } else {
          responseEntity
              .setCode(HttpStatus.ERROR)
              .setData(null)
              .setMessage("租户删除失败");
        }
      } else {
        responseEntity
            .setCode(HttpStatus.ERROR)
            .setData(null)
            .setMessage("租户不存在");
      }
    } catch (Exception e) {
      responseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return responseEntity;
    }
  }


  @ApiOperation("展示所有未被删除的租户")
  @RequestMapping(value = "/showTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showAllTenements() {
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      List<Tenement> tenements = tenementService.queryExistTenement();
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(tenements)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }

  @ApiOperation("模糊查询所有未被删除的租户")
  @RequestMapping(value = "/showQueryTenement", method = RequestMethod.POST, headers = "Accept=application/json")
  public HttpResponseEntity showQueryTenements(@RequestBody Map<String, Object> map) {
//    System.out.println(map.get("queryStr").toString() + "   111   ");
    HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
    try {
      List<Tenement> tenements = tenementService.queryTenementByName(
          map.get("queryStr").toString());
      httpResponseEntity
          .setCode(HttpStatus.SUCCESS)
          .setData(tenements)
          .setMessage("success");
    } catch (Exception e) {
      httpResponseEntity
          .setCode(HttpStatus.ERROR)
          .setData(null)
          .setMessage(e.getMessage());
    } finally {
      return httpResponseEntity;
    }
  }


}
